package com.bawei.module_mine.viewmodel

import com.bawei.lib_common.base.BaseViewModel
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading
import com.bawei.lib_common.base.state.RequestEvent
import com.bawei.lib_common.base.state.Success
import com.bawei.lib_storage.AppMMKV
import com.bawei.lib_storage.AuthMMKV
import com.bawei.module_mine.repository.LoginRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import javax.inject.Inject

@HiltViewModel
class LoginViewModel @Inject constructor(private val repository: LoginRepository):BaseViewModel(){
    val username:MutableStateFlow<String> = MutableStateFlow("")
    val password:MutableStateFlow<String> = MutableStateFlow("")
    private val _mNotice=MutableStateFlow<RequestEvent>(Loading)
    val noticeState
        get() =_mNotice.asStateFlow()

    fun login(username:String,password:String){
        execute(
            action = repository.login(username, password),
            onStart = {
                _mNotice.value=Loading
            },
            onError = {
                _mNotice.value=Failed(it)
            },
            onFinish = {
                _mNotice.value=Success
                AuthMMKV.token=it.data.token
                AppMMKV.token=it.data.token
                AppMMKV.userId=it.data.id
                AppMMKV.username=it.data.username
                AuthMMKV.isSignInA=false
                AuthMMKV.isSignInB=false
            }
        )
    }

}